window.form=(function($){
	var layer=window.layer?window.layer:false;
	var shade=true;
	var form={};	
	var uploadfile=[];
	var extra=null;
	function showSuccess(formname,name,message){		
		var b= $(document[formname][name]);
		b.parents(".form-group").removeClass("has-error");
		b.parents(".form-group").addClass("has-success");
		if(b.parent().hasClass("input-group")){
			b=b.parent();
		}
		b.nextAll(".error").addClass("hide");
		b.nextAll(".success").removeClass("hide");
		if(message){
			b.nextAll(".success").html("<i class=\"glyphicon glyphicon-ok\"></i> "+message)
		}else{
			b.nextAll(".success").html("")
		}
	}
	function showError(formname,name,message){
		var b= $(document[formname][name]);
		b.parents(".form-group").removeClass("has-success");
		b.parents(".form-group").addClass("has-error");
		if(b.parent().hasClass("input-group")){
			b=b.parent();
		}	
		b.nextAll(".success").addClass("hide");
		b.nextAll(".error").removeClass("hide");
		if(message){
			b.nextAll(".error").html("<i class=\"glyphicon glyphicon-remove\"></i> "+message)
		}else{
			b.nextAll(".error").html("<i class=\"glyphicon glyphicon-remove\"></i> 出错")
		}		
	}	
	function showFocus(formname,name){
		var b= $(document[formname][name]);
		b.focus();
	}
	
	function showFileError(formname,name,message){
		var r=$("form[name='"+formname+"'] .dropzone[name='"+name+"']");
		r.parents(".form-group").removeClass("has-success");
		r.parents(".form-group").addClass("has-error");
		r.nextAll(".success").addClass("hide");
		r.nextAll(".error").removeClass("hide");			
		if(message){
			r.nextAll(".error").html("<i class=\"glyphicon glyphicon-remove\"></i> "+message)
		}else{
			r.nextAll(".error").html("<i class=\"glyphicon glyphicon-remove\"></i> 出错")
		}	
	}
	
	function showFileSuccess(formname,name,message){
		var r=$("form[name='"+formname+"'] .dropzone[name='"+name+"']");
		r.parents(".form-group").removeClass("has-error");
		r.parents(".form-group").addClass("has-success");
		r.nextAll(".error").addClass("hide");
		r.nextAll(".success").removeClass("hide");
		if(message){
			b.nextAll(".success").html("<i class=\"glyphicon glyphicon-ok\"></i> "+message)
		}else{
			b.nextAll(".success").html("")
		}
	}
	
	function isUploadFile(formname,name){
		var b=false;
		$("form[name='"+formname+"'] .dropzone").each(function(){
			var n=$(this).attr("name");	
			if(n==name){
				b=true; 
			}
		});
		return b;
	}
	
	function checkForm(val,attribute){
			if(!attribute){
				return false;
			}
			if(attribute.indexOf("unempty")!=-1 && val==""){
				return "输入内容不能为空！";
			}
			if(attribute.indexOf(" gt")!=-1){
				var gt=attribute.split(" ");
				var t=0;
				for(var l in gt){					
					var p=parseInt(gt[l].substr(2));				
					if(t<p)t=p;
				}
				if(val.length<t){
					return "输入内容长度必须大于"+t+"！";
				}
			}
			if(attribute.indexOf(" lt")!=-1){
				var lt=attribute.split(" ");
				var t=99999;
				for(var l in lt){					
					var p=parseInt(lt[l].substr(2));				
					if(t>p)t=p;
				}
				if(val.length>t){
					return "输入内容长度必须小于"+t+"！";
				}
			}
			if(attribute.indexOf("number")!=-1 && isNaN(val)){
				return "输入内容必须为数字！";
			}
			if(attribute.indexOf("integer")!=-1){
				var reg1 =/^[-+]?\d*$/;
				if(val.trim().match(reg1) == null){
					return "输入内容必须为整数！";
				}		
			}
			if(attribute.indexOf("+integer")!=-1){
				var reg1 =  /^\d+$/;
				if(val.trim().match(reg1) == null)
				return "输入内容必须为大于0的整数！";
			}
			if(attribute.indexOf("unchinaChar")!=-1){
				for(var i=0;i<val.length;i++){
					var s=val.charAt(i);
					var reg1 = /[\u4e00-\u9fa5]{1}/;  			
					if(reg1.test(s)){
						return "输入内容不能包含中文！";
					}					
				}	
			}
			if(attribute.indexOf("unNum")!=-1 && !isNaN(val)){
				return "输入内容不能为数字！";
			}
			if(attribute.indexOf("email")!=-1 && val!=""){	
				var szReg=/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org|info|cc|tv)$/; 
				var c=szReg.test(val); 
				if(!c)
				return "输入内容不是邮件！";
			}
			if(attribute.indexOf("mobile")!=-1 && val!=""){
				var reg = /^1[3|4|5|7|8][0-9]{9}$/; 
				var flag = reg.test(val);
				if(!flag)
				return "输入内容不是手机号！";
			}
			if(attribute.indexOf("idcard")!=-1 && val!=""){				
				var tip = IdentityCodeValid(val);
				if(tip!="")
				return tip;
			}
			if(attribute.indexOf("specialchar")!=-1 && val!=""){				
				var specialKey = "`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./！￥…（）—【】《》？，。“”‘’；：";
				for(var i=0;i<specialKey.length;i++){
					var s=specialKey.charAt(i);
					if(val.indexOf(s)!=-1){
						return "输入内容不能包含特殊字符！";
					}
				}
			}
			
			return false;
	}
	function IdentityCodeValid(code) { 
         var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
         var tip = "";
         if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){
             tip = "身份证号格式错误";
         }else if(!city[code.substr(0,2)]){
             tip = "身份证号地址编码错误";
         }else{
             if(code.length == 18){
                 code = code.split('');
                 var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                 var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                 var sum = 0;
                 var ai = 0;
                 var wi = 0;
                 for (var i = 0; i < 17; i++){
                     ai = code[i];
                     wi = factor[i];
                     sum += ai * wi;
                 }
                 var last = parity[sum % 11];
                 if(parity[sum % 11] != code[17]){
                     tip = "身份证号校验位错误";
                 }
             }
         }        
         return tip;
    }
	
	function dropzone(element){			
		var maxFilesize=$(element).attr("maxFilesize");
		var url=$(element).attr("url");
		var maxFiles=$(element).attr("maxFiles");
		var minFiles=$(element).attr("minFiles");
		var acceptedFiles=$(element).attr("acceptedFiles");	
		var formname=$(element).attr("name");	
		var initimg=$(element).attr("initimg");	
		var _initimg=[];
		if(initimg){
			_initimg=JSON.parse(initimg);
			for(var i=0;i<_initimg.length;i++){
				_initimg[i].formname=formname;
				uploadfile.push(_initimg[i]);
			}		
		}	
		$(element).dropzone({								    
			paramName: "uploadFileName",								    
			maxFilesize: maxFilesize,		
			url:url,																		
			addRemoveLinks : true,									
			maxFiles:maxFiles,									
			acceptedFiles:acceptedFiles,											
			dictResponseError: '上传失败!',									
			init: function(){
				var e=$(element).children(".dz-message");
				if(_initimg.length>0){
					this.emit("initimage", _initimg);	
					e.addClass("hide");	
				}										
				this.on("addedfile", function(file){	
					e.addClass("hide");					
				});
				this.on("removedfile", function(file){
					for(var i=0; i<uploadfile.length; i++) {
					    if(uploadfile[i].id == file.id) {
					       uploadfile.splice(i, 1);
					       break;
					    }
					}	
					var b=true;
					for(var i=0; i<uploadfile.length; i++) {
					    if(uploadfile[i].formname==formname){
					    	b=false;
					    }
					}
					if(b){
						e.removeClass("hide");
					}
				});
				this.on("success",function(file, responseText){					
					if(responseText.error==1){
						if(layer){
							layer.msg(responseText.message);
						}else{
							alert(responseText.message);
						}
						return;
					}else{	
						file.url=responseText.url;
						file.id=responseText.id;	
						file.formname=formname;
						uploadfile.push(file);
					}					
				});
			}								 
		});		
	}
	function getNextAreas(element){
		var e=$(element).parent().next().children("select");
		return e;
	}
	function getJsonData(id,element,df){	
		var s=$(element).attr("name");
		var url=$(element).attr("url")+"admin/common/areas?id="+id;
		$.ajax({
	        url: url,
	        dataType: 'json',
	        type:'get',
	        async:false,
	        error:function(){"多级地址必须安装后台才能使用！"},
	        success: function (res) {
	           if(res.length==0){
	        	   return;
	           }
	           var str="";
	           if(s=='s_province'){
	        	   str+="<option value=\"0\">省份</option>";
	        	   $(getNextAreas(element)).html("<option value=\"0\">地级市</option>"); 
	        	   $(getNextAreas(getNextAreas(element))).html("<option value=\"0\">区、县级市</option>"); 
	        	   $(getNextAreas(getNextAreas(getNextAreas(element)))).html("<option value=\"0\">镇、乡、街道</option>");
	           }
	           if(s=='s_city'){
	        	   str+="<option value=\"0\">地级市</option>";
	        	   $(getNextAreas(element)).html("<option value=\"0\">区、县级市</option>"); 
	        	   $(getNextAreas(getNextAreas(element))).html("<option value=\"0\">镇、乡、街道</option>");
	           }
			   if(s=='s_county'){
				   str+="<option value=\"0\">区、县级市</option>";
				   $(getNextAreas(element)).html("<option value=\"0\">镇、乡、街道</option>");
	           }
			   if(s=='s_street'){
				   str+="<option value=\"0\">镇、乡、街道</option>";
	           }
	           for(var i=0;i<res.length;i++){
	        	   if(df && res[i].id==df){
	        		   str+="<option selected value=\""+res[i].id+"\">"+res[i].name+"</option>";
	        	   }else{
	        		   str+="<option value=\""+res[i].id+"\">"+res[i].name+"</option>";
	        	   }       	  		        	
	           }
	           $(element).html(str);
	        }		
	    });	
	}
	var SelectedForm=function(name){
		this.name=name;
		this.submit;
		this.error;
		this.success;
		this.focus;
		this.callback=[];
	}
	form.init=function(formname){	
		$(".form-group .success").remove();
		$(".form-group .error").remove();
		$(".form-group").removeClass("has-success");
		$(".form-group").removeClass("has-error");	
		var o=new SelectedForm(formname);	
		$("form[name='"+formname+"'] .form-control").each(function(){	
			if($(this).hasClass("notVerifying")){
				return;
			}
			var attribute=$(this).attr("attribute");
			var name=$(this).attr("name");	
			
			var str="<span class=\"help-block success hide\"><i class=\"fa fa-ok\"></i></span>";
			var group=$(this).parent().hasClass("input-group");
			if(group){
				$(this).parent().after(str);	
			}else{
				$(this).after(str);	
			}	
			var str="<span class=\"help-block error hide\"><i class=\"fa fa-remove\"></i></span>";
			if(group){
				$(this).parent().after(str);	
			}else{
				$(this).after(str);	
			}				
			if(this.tagName=="INPUT" && this.type=="text"){
				$(this).blur(function(){	
					var val=$(this).val();
					var r=checkForm(val,attribute);
					if(r!==false){
						showError(formname,name,r);
					}else{
						showSuccess(formname,name);
					}
				});	
			}
			if(this.tagName=="INPUT" && this.type=="password"){
				$(this).blur(function(){	
					var val=$(this).val();
					var r=checkForm(val,attribute);
					if(r!==false){
						showError(formname,name,r);
					}else{
						showSuccess(formname,name);
					}
				});	
			}
            if(this.tagName=="TEXTAREA"){
				    var maxnum=$(this).attr("maxnum");
					if(maxnum!=0){
						$(this).keyup(function(){						
							var val=$(this).val();
							if(val.length>maxnum){
								showError(formname,name,"超出了"+(val.length-maxnum)+"个字");
							}else{
								showSuccess(formname,name,"还能输入"+(maxnum-val.length)+"个字");
							}
						}); 						
					}               									
			}
			if(this.tagName=="INPUT" && this.type=="radio"){
					
			}
			if(this.tagName=="INPUT" && this.type=="checkbox"){
							
			}				
			if(this.tagName=="SELECT" && this.name=="s_province"){
				getJsonData($(this).attr("parent"),this,$(this).attr("default"));				
				$("select[name='s_province']").change(function(){
					var id=$(this).val();	
					var e=getNextAreas(this);
					if(e.length>0)getJsonData(id,e,$(this).attr("default")); 									   
				});
			}else if(this.tagName=="SELECT" && this.name=="s_city"){
				if($(this).attr("parent")){
					getJsonData($(this).attr("parent"),this,$(this).attr("default"));	
				}
				$("select[name='s_city']").change(function(){
					var id=$(this).val();
					var e=getNextAreas(this);
					if(e.length>0)getJsonData(id,e,$(this).attr("default")); 
				});
			}else if(this.tagName=="SELECT" && this.name=="s_county"){
				if($(this).attr("parent")){
					getJsonData($(this).attr("parent"),this,$(this).attr("default"));	
				}		
				$("select[name='s_county']").change(function(){
					var id=$(this).val();	
					var e=getNextAreas(this);
					if(e.length>0)getJsonData(id,e,$(this).attr("default")); 									   
				});				
			}else if(this.tagName=="SELECT" && this.name=="s_street"){
				if($(this).attr("parent")){
					getJsonData($(this).attr("parent"),this,$(this).attr("default"));	
				}									
			}else if(this.tagName=="SELECT"){
				$(this).change(function(){	
					var val=$(this).val();
					var r=checkForm(val,attribute);
					if(r!==false){
						showError(formname,name,r);
					}else{
						showSuccess(formname,name);
					}
				});								
			}
			if(this.tagName=="INPUT" && $(this).hasClass('calendar')){
				var k=document.getElementsByClassName('calendar');
					for(var i1=0;i1<k.length;i1++){
						var months=$(k[i1]).attr('months');
						var mode=$(k[i1]).attr('mode');
						var direction=$(k[i1]).attr('direction');
						$(k[i1]).attr('id','Kalendae'+i1);
						new Kalendae.Input('Kalendae'+i1, {
							months:months,
							mode:mode,
							direction:direction
					});		
				}	
			}	
			if(this.tagName=="INPUT" && $(this).hasClass('timepicker')){
				var _this=this;
				$(this).next(".input-group-addon").click(function(){		
					$(_this).val("");
				});
				var format=$(this).attr("format");
				var daysOfWeekDisabled=$(this).attr("daysOfWeekDisabled");
				var startView=parseInt($(this).attr("startView"));
				var obj={
					format:format,
				    language: 'zh-CN',
				    weekStart: 1,
				    daysOfWeekDisabled:daysOfWeekDisabled,
				    todayBtn: 1,
				    autoclose: 1,
				    todayHighlight: 1,
				    startView: startView,
				    minView: startView,
				    //forceParse: 0
				};				
				var startDate=$(this).attr("startDate");
				if(startDate){
					alert(1);
					obj.startDate=startDate;
				}
				var endDate=$(this).attr("endDate");
				if(endDate){
					alert(2);
					obj.endDate=endDate;
				}
				$(this).datetimepicker(obj);
			}	
		});	
		
		$(".dropzone").each(function(){
			var str="<span class=\"help-block success hide\"><i class=\"fa fa-ok\"></i></span>";
			$(this).after(str);	
			var str="<span class=\"help-block error hide\"><i class=\"fa fa-remove\"></i></span>";
			$(this).after(str);
			dropzone(this);
		});
		
		return o;
	}
	//提交
	SelectedForm.prototype.submit=function(callback){	
		for(var i=0;i<this.callback.length;i++){
			var c=this.callback[i]();
			if(!c){
				return;
			}
		}
		var formname=this.name;
		var f=true;
		$("form[name='"+formname+"'] .form-control").each(function(){
			var attribute=$(this).attr("attribute");
			var val=$(this).val();
			var name=$(this).attr("name");	
			var r=checkForm(val,attribute);
			if(r!==false){
				showError(formname,name,r);	
				showFocus(formname,name);
				f=false;
			}			
		});	
		$("form[name='"+formname+"'] .dropzone").each(function(){
			var name=$(this).attr("name");
			var minFiles=$(this).attr("minFiles");
			var n=0;
			for(var i=0; i<uploadfile.length; i++) {
			    if(uploadfile[i].formname==name){
			    	n++;
			    }
			}
			if(n<minFiles){
				showFileError(formname,name,"至少上传"+minFiles+"个文件");
				f=false;
			}				
		});
		if(f){
			if(uploadfile.length>0){
				for(var i=0;i<uploadfile.length;i++){
					var input=document.createElement("input");
					var data={url:uploadfile[i].url,type:uploadfile[i].type,name:uploadfile[i].name,id:uploadfile[i].id,size:uploadfile[i].size}
					input.name=uploadfile[i].formname;
					input.type="hidden";					
					input.value=JSON.stringify(data);
					$(input).addClass("hiddenInput");
					$(document[this.name]).append(input);
				}			
			}	
			if(extra!=null){
				for(var key in extra){
					var input=document.createElement("input");
					input.name=key;
					input.type="hidden";					
					input.value=extra[key];
					$(input).addClass("hiddenInput");
					$(document[this.name]).append(input);
				}
			}
			var method=$(document[this.name]).attr("method");
			var _sd=$(document[this.name]).attr("shade");
			if(_sd=='false'){
				shade=false;
			}
			if(method=='ajax' || method=='AJAX'){
				if(layer && shade){
					var shadeindex = layer.load(1);
				}
				var action=$(document[formname]).attr("action");
				var data=$("form[name='"+formname+"'] input,form[name='"+formname+"'] textarea,form[name='"+formname+"'] select");
				var postdata={};
				for(var i=0;i<data.length;i++){
					if(data[i].type=='radio' && !data[i].checked){
						continue;
					}
					if(data[i].type=='checkbox' && !data[i].checked){
						continue;
					}
					if(data[i].name && !postdata[data[i].name]){
						postdata[data[i].name]=[];
						postdata[data[i].name].push(data[i].value);
					}else if(data[i].name && postdata[data[i].name]){
						postdata[data[i].name].push(data[i].value);
					}else{
						continue;
					}									
				}
				for(var m in postdata){
					if(postdata[m].length==1){
						postdata[m]=postdata[m][0];
					}
				}
	        	$(".hiddenInput").remove();
				$.ajax({
					url: action,
			        dataType: 'json',
			        type:'post',
			        data:postdata,
			        traditional:true,
			        success: function (res) {	  
			        	if(layer && shade){
			        		layer.close(shadeindex);
						}
			        	if(callback){
			        		callback(res);
			        		return;
			        	}
			        }
				});
			}else{
				document[this.name].submit();
			}			
		}	
	}
	//提示错误
	SelectedForm.prototype.error=function(name,message){
		var b=isUploadFile(this.name,name);		
		if(b){
			showFileError(this.name,name,message);
			return;
		}
		showError(this.name,name,message);
	}
	//重置
	SelectedForm.prototype.reset=function(){
		uploadfile=[];
		form.init(this.name);
	}
	//
	SelectedForm.prototype.check=function(value,attribute){
		var r=checkForm(value,attribute);
		return r;
	}
	//提示成功
	SelectedForm.prototype.success=function(name,message){
		var b=isUploadFile(this.name,name);		
		if(b){
			showFileSuccess(this.name,name,message);
			return;
		}
		showSuccess(this.name,name,message);
	}
	//获取焦点
	SelectedForm.prototype.focus=function(name){
		var b=isUploadFile(this.name,name);		
		if(b){
			var r=$("form[name='"+this.name+"'] .dropzone[name='"+name+"']");
			$(r[0]).attr("tabindex",0);
			$(r[0]).focus();
			return;
		}
		showFocus(this.name,name);
	}
	//获取值
	SelectedForm.prototype.getValue=function(name){
		var r=[];
		for(var i=0;i<uploadfile.length;i++){
			if(uploadfile[i].formname==name){
				var data={url:uploadfile[i].url,type:uploadfile[i].type,name:uploadfile[i].name,id:uploadfile[i].id,formname:uploadfile[i].formname};
				r.push(data);
			}
		}	
		var b=isUploadFile(this.name,name);		
		if(b)return r;
		return document[this.name][name].value;
	}
	//判断有无错误
	SelectedForm.prototype.hasError=function(){
		var b=$(document[this.name]).children().find(".has-error");
		if(b.length>0){
			return true;
		}
		return false;
	}	
	//添加值
	SelectedForm.prototype.put=function(key,value){
		if(extra==null){
			extra={};
		}
		extra[key]=value;
	}	
	//添加值
	SelectedForm.prototype.onsubmit=function(res){
		this.callback.push(res);
	}
	
	return form;
})($)
